# 导入蓝图
from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template



@index_blu.route("/newslist")
def get_news_list():
    """新闻列表后端实现"""

    # 1.获取参数
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)

    # 2.转换参数类型
    try:
        page = int(page)

        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    # 3.查询数据库
    try:

        # 判断分类编号是否不等于1
        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")

    # 4.获取到分页对象中的内容
    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    # 5.将对象列表,转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    # 6.返回响应,携带数据
    return jsonify(errno=RET.OK, errmsg="查询成功", totalPage=totalPage, currentPage=currentPage, newsList=news_list)


# 使用蓝图进行装饰主页的视图函数

@index_blu.route("/", methods=["GET", "POST"])
@user_login_data
def index():
    # 1 获取请求首页的用户id 看是否可以获取到
    # 1.1 使用装饰器添加user到g变量代替查询
    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 如果获取到用户信息，把用户信息传到模板进行渲染

    # 2 获取点击排行数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 把遍历出来的对象转化为字典对象
    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    # 3 获取新闻分类数据
    categories = Category.query.all()
    # 定义列表保存分类数据
    categories_dicts = []

    for category in categories:
        # 拼接内容
        categories_dicts.append(category.to_dict())

    data = {
        "user_info": g.user.to_dict() if g.user else None,
        "click_news_list": click_news_list,
        "categories": categories_dicts,
    }



    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def favicon():
    print("111")
    return current_app.send_static_file("news/favicon.ico")



